<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>设备管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="row-play">
      <div class="row-play-t">分类名称：</div>
      <el-autocomplete
          v-model="searchForm.categoryName"
          :fetch-suggestions="querySearchAsyncCategoryName"
          placeholder="请输入内容"
          size="small"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">设备名称：</div>
      <el-autocomplete
          v-model="searchForm.name"
          :fetch-suggestions="querySearchAsyncDeviceName"
          placeholder="请输入内容"
          size="small"
          style="width: 160px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">版本号：</div>
      <el-autocomplete
          v-model="searchForm.version"
          :fetch-suggestions="querySearchAsyncDeviceVersion"
          placeholder="请输入格式：x.x.x"
          size="small"
          style="width: 180px;margin-right: 10px;"
          :maxlength="15"
          show-word-limit
      ></el-autocomplete>
      <div class="row-play-t">设备状态：</div>
      <el-select class="row-play-p" v-model="searchForm.status" placeholder="请选择" size="small"
                 style="width: 100px;margin-right: 10px;">
        <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
        </el-option>
      </el-select>
      <!--      分类名称：-->
      <!--      <el-input class="row-play-play" v-model="name" placeholder="请输入内容"></el-input>-->
      <el-button @click="getPage" size="small">搜索</el-button>
      <el-button @click="add" size="small">新增</el-button>
      <el-button @click="toggleSelection()" size="small">取消选择</el-button>
      <el-button @click="deleteMany" size="small" type="danger">批量删除</el-button>
    </div>
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="修改时间"
          width="180">
        <template slot-scope="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column
          label="设备名称"
          width="120">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>创建人：{{ scope.row.createUserName }}</p>
            <p>创建时间: {{ scope.row.createTime }}</p>
            <p>修改人: {{ scope.row.updateUserName }}</p>
            <p>修改时间: {{ scope.row.updateTime }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
          label="图片"
          width="120">
        <template slot-scope="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.image"
              :preview-src-list=[scope.row.image]>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
          label="版本号"
          width="100">
        <template slot-scope="scope">
          {{ scope.row.version }}
        </template>
      </el-table-column>
      <el-table-column
          label="分类名称"
          width="100">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column
          label="状态"
          width="100">
        <template slot-scope="scope">
          <el-switch
              @change="editStatus(scope.row)"
              style="display: block;height: 30px;"
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="edit(scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize">
      </el-pagination>
    </div>
    <el-dialog title="新增设备" :visible.sync="dialogAddFormVisible">
      <el-form ref="formRef" :model="addForm" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.categoryName"
              :fetch-suggestions="querySearchAsyncCategoryName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="设备名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="addForm.name"
              :fetch-suggestions="querySearchAsyncDeviceName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" style="width: 400px" prop="version">
          <el-input v-model="addForm.version" placeholder="请输入版本号：x.x.x" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="addForm.status" size="mini" disabled
                     style="width: 100px;">
            <!--            <el-option label="上线" :value="1"></el-option>-->
            <el-option label="下线" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片上传" :label-width="formLabelWidth" style="width: 300px">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="customHeaders"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="successUpload"
          >
            <img v-if="addForm.image" :src="addForm.image" class="avatar" alt="图片错误">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDevice">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑设备" :visible.sync="dialogEditFormVisible">
      <el-form ref="formRef" :model="editForm" :rules="formRules">
        <el-form-item label="分类名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="editForm.categoryName"
              :fetch-suggestions="querySearchAsyncCategoryName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="设备名称" :label-width="formLabelWidth" style="width: 400px">
          <el-autocomplete
              v-model="editForm.name"
              :fetch-suggestions="querySearchAsyncDeviceName"
              placeholder="请输入内容"
              size="mini"
              style="width: 160px;margin-right: 10px;"
              :maxlength=maxlength
              :minlength=minlength
              show-word-limit
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" style="width: 400px" prop="version">
          <el-input v-model="editForm.version" placeholder="请输入版本号：x.x.x" size="mini"></el-input>
        </el-form-item>
        <el-form-item label="图片上传" :label-width="formLabelWidth" style="width: 300px">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="customHeaders"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="successUpload"
          >
            <img v-if="editForm.image" :src="editForm.image" class="avatar" alt="图片错误">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDevice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      maxlength: 15,
      minlength: 1,
      statusList: [{
        value: 0,
        label: '下线'
      }, {
        value: 1,
        label: '在线'
      }, {
        value: null,
        label: ''
      }],
      tableData: [],
      multipleSelection: [],
      currentPage: 1,
      pageSize: 10,
      totalSize: 0,
      dialogAddFormVisible: false,
      dialogEditFormVisible: false,
      formLabelWidth: '120px',
      addForm: {
        name: '',
        version: '',
        image: '',
        status: 0,
        categoryName: ''
      },
      searchForm: {
        name: '',
        version: '',
        status: null,
        categoryName: ''
      },
      editForm: {
        id: null,
        name: '',
        version: '',
        image: '',
        status: null,
        categoryName: ''
      },
      formRules: {
        version: [{required: true, message: '请输入版本号', trigger: 'blur'},
          {min: 1, max: 15, message: '长度在一到十五个字符之间', trigger: 'blur'}]
      },
      restaurants: [],
      categoryNameList: [],
      deviceNameList: [],
      deviceVersionList: [],
      customHeaders: {
        Token: window.sessionStorage.getItem('token')
      },
      uploadUrl: 'http://localhost:8081/aliOss/upload'
    }
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/device/" + row.id);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.getPage();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getPage();
    },
    async getPage() {
      const {data: res} = await this.$http.get("/device/page", {
        params: {
          page: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchForm.status,
          name: this.searchForm.name,
          categoryName: this.searchForm.categoryName,
          version: this.searchForm.version
        }
      });
      if (res.code === 0) {
        return this.$message.error("获取设备分类信息失败");
      }
      this.tableData = res.data.records;
      this.totalSize = res.data.total;
      await this.getCategoryNameList();
      await this.getDeviceNameVersionList();
    },
    async editStatus(row) {
      this.$refs.multipleTable.doLayout();
      const {data: res} = await this.$http.put("/device/updateStatus", {
        id: row.id,
        status: row.status
      });
      if (res.code === 0) {
        await this.getPage();
        return this.$message.error(res.msg);
      }
      this.$message({
        type: 'success',
        message: '修改成功!'
      });
    },
    deleteMany() {
      let ids = [];
      this.multipleSelection.forEach(row => {
        ids.push(row.id);
      })
      let idss = ids.join(',');
      this.$confirm('此操作将永久删除多个设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async () => {
        const {data: res} = await this.$http.delete("/device", {
          params: {
            ids: idss
          }
        });
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        await this.getPage();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    add() {
      this.dialogAddFormVisible = true;
    },
    addDevice() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogAddFormVisible = false;
        const {data: res} = await this.$http.post("/device/add", this.addForm);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        this.$message.success("添加成功");
        await this.getPage();
      })
    },
    edit(row) {
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.version = row.version;
      this.editForm.categoryName = row.categoryName;
      this.editForm.image = row.image;
      this.editForm.status = row.status;
      this.dialogEditFormVisible = true;
    },
    editDevice() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return false;
        this.dialogEditFormVisible = false;
        const {data: res} = await this.$http.put("/device/edit", this.editForm);
        if (res.code === 0) {
          return this.$message.error(res.msg);
        }
        this.$message.success("编辑成功");
        await this.getPage();
      })
    },
    querySearchAsyncCategoryName(queryString, callback) {
      var categoryNameList = this.categoryNameList;
      var results = queryString ? categoryNameList.filter(this.createStateFilter(queryString)) : categoryNameList;
      callback(results);
    },
    querySearchAsyncDeviceName(queryString, callback) {
      var deviceNameList = this.deviceNameList;
      var results = queryString ? deviceNameList.filter(this.createStateFilter(queryString)) : deviceNameList;
      callback(results);
    },
    querySearchAsyncDeviceVersion(queryString, callback) {
      var deviceVersionList = this.deviceVersionList;
      var results = queryString ? deviceVersionList.filter(this.createStateFilter(queryString)) : deviceVersionList;
      callback(results);
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    beforeAvatarUpload(file) {
      let index = file.name.lastIndexOf(".");
      let extension = file.name.substr(index + 1);
      let extensionList = [
        "png",
        "PNG",
        "jpg",
        "JPG",
        "jpeg",
        "JPEG",
        "bmp",
        "BMP",
      ];
      if (extensionList.indexOf(extension) < 0) {
        this.$message({
          message: "当前文件格式不支持",
          type: "error",
          center: true,
        });

        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
    },
    successUpload(response) {
      this.addForm.image = response.data;
    },
    async getCategoryNameList() {
      const {data: res} = await this.$http.get("/category/nameList");
      if (res.code === 0) {
        return this.$message.error(res.msg);
      }
      this.categoryNameList = res.data;
    },
    async getDeviceNameVersionList() {
      const {data: res} = await this.$http.get("/device/nameVersionList");
      if (res.code === 0) {
        return this.$message.error("获取设备名和设备版本失败");
      }
      if (res.data !== null) {
        this.deviceNameList = res.data.nameSet;
        this.deviceVersionList = res.data.versionSet;
      }
    },
  initWebSocket() {
    // 创建 WebSocket 对象
    this.websocket = new WebSocket('ws://127.0.0.1:8081/im/server/2');

    // 监听 WebSocket 连接成功事件
    this.websocket.onopen = () => {
      console.log('WebSocket 连接成功');
    };

    // 监听 WebSocket 接收消息事件
    this.websocket.onmessage = (event) => {
      const message = event.data;
      console.log('收到服务器消息:', message);

      // 解析消息并进行处理
      const parsedMessage = JSON.parse(message);
      const msg=parsedMessage.msg;
      this.$notify({
        title: '请及时处理',
        message: msg,
        type: 'warning',
        duration: 0
      });
      // const temper = parsedMessage.notify_data.body.services[0].properties.temper;
      // const humidness = parsedMessage.notify_data.body.services[0].properties.humidness;
      // console.log(temper);
      // 将 temper 值添加到 tableData 数组中
      // this.tableData.push({ temper, humidness, value: '其他数值' });
    };

    // 监听 WebSocket 连接关闭事件
    this.websocket.onclose = () => {
      console.log('WebSocket 连接关闭');
    };

    // 监听 WebSocket 错误事件
    this.websocket.onerror = (error) => {
      console.error('WebSocket 错误:', error);
    };
  }
  },
  mounted() {
    this.getPage();
    this.initWebSocket();
  }
}
</script>

<style lang="less" scoped>
.row-play {
  display: flex;
  align-items: center;

  .row-play-p {
    margin-right: 20px;
  }

  .row-play-t {
    font-size: 10px;
  }
}

.block {
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  :hover {
    border-color: #409EFF;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>